/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.planning.tactical;

import java.beans.IntrospectionException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import nl.cloudfarming.client.model.FieldPlan;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;

/**
 * Factory which provides FieldPlanNodes.
 * @author Timon Veenstra
 */
public class FieldPlanNodeFactory extends ChildFactory<FieldPlan> implements PropertyChangeListener {

    private TacticalPlanningService service;

    public FieldPlanNodeFactory() {
    }


    /**
     * gets the TacticalPlanningService at the same time it registers itself as a lookup Listener of the Noderefreshevent class
     * @return 
     */
    public final TacticalPlanningService getService() {
        if (service == null) {
            service = Lookup.getDefault().lookup(TacticalPlanningService.class);
            service.addPropertyChangeListener(TacticalPlanningService.FIELDPLAN_ENTITY, this);
        }
        return service;
    }
    
    public void setService(TacticalPlanningService service){
        this.service = service;
    }

    @Override
    protected Node createNodeForKey(FieldPlan key) {
        try {
            return new FieldPlanNode(key, service);
        } catch (IntrospectionException ex) {
            Exceptions.printStackTrace(ex);
            return null;
        }
    }

    @Override
    protected boolean createKeys(List<FieldPlan> toPopulate) {
        toPopulate.addAll(getService().findAllFieldPlans());
        return true;
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        refresh(true);
    }


}
